#!/usr/bin/python
import argparse

def cut(gfa, ctg_id, sublen, output):
    fo = open(output,"w")
    with open(gfa) as f:
        for line in f:
            l = line.strip().split()
            if l[1] != ctg_id:
                fo.write(line)
            elif l[0] == 'S':
                s = l[2][0:sublen]
                fo.write('\t'.join((l[0],l[1],s)))
                fo.write("\n")
                s = l[2][sublen:]

            elif l[0] == 'A' and int(l[2]) <= sublen :
                fo.write(line)
            elif l[0] == 'A' and int(l[2]) >= sublen and s != '':
                id_ = l[1]+'1'
                fo.write('\t'.join(('S',id_,s)))
                fo.write("\n")
                line = line.replace(l[1],id_)
                fo.write(line)
                s = ''
            elif l[0] == 'A' and int(l[2]) >= sublen and s == '':
                line = line.replace(l[1],id_)
                fo.write(line)

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    parser =  argparse.ArgumentParser(usage = """
    cutgfa.py  --gfa_fn GFA --ctg CTG --pos POS  --output OUT
    """,description = "overlap data filter")
    parser.add_argument('--gfa_fn',type=str,help="Input. gfa file",required = True)
    parser.add_argument('--ctg',type=str,help="ctg to cut.")
    parser.add_argument('--pos',type=int,help="pos to cut",required = True)
    parser.add_argument('--output',type=str,help="Output filename",required = True)
    arg = vars(parser.parse_args())
    gfa = arg["gfa_fn"]
    ctg_id = arg["ctg"]
    sublen = arg["pos"]
    output = arg["output"]
    cut(gfa, ctg_id, sublen, output)
